using System.Collections.Generic;
using System.IO;
using System.Linq;
using MediaAssistant.DAL;

namespace MediaFS.Data
{
    public class MediaFolder : MemoryFolder
    {
        public MediaFolder(MemoryFolder parent, string name) : base(parent, name)
        {
        }

        private volatile List<MemoryItem> _children; 
        public override List<MemoryItem> Children
        {
            get
            {
                if(_children==null)
                {
                    lock (this)
                    {
                        if(_children==null)
                        {
                            _children=new List<MemoryItem>();
                            LoadChildren();
                        }
                    }
                }
                return _children;
            }
        }

        private void LoadChildren()
        {
            var libraryItem = (LibraryItem)Tag;
            if(libraryItem==null)
                return;
            lock (DatabaseManager.LockObject)
            {
                foreach (var child in libraryItem.Children.Where(c => c.IsEmpty() == false))
                {
                    new MediaFolder(this, child.Title) { Tag = child };
                }
                foreach (var movie in libraryItem.Movies)
                {
                    var actualFileName = movie.GetFileToPlay();
                    if (string.IsNullOrEmpty(actualFileName) == false && File.Exists(actualFileName))
                    {
                        MediaFile.Create(this, actualFileName).Tag = movie;
                    }
                }
                foreach (var music in libraryItem.Musics)
                {
                    var actualFileName = music.FullPath;
                    if (string.IsNullOrEmpty(actualFileName) == false && File.Exists(actualFileName))
                    {
                        MediaFile.Create(this, actualFileName).Tag = music;
                    }
                }    
            }
        }
    }
}